package com.gzist.security4.web;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gzist.security4.domain.Permission;
import com.gzist.security4.domain.Role;
import com.gzist.security4.domain.User;
import com.gzist.security4.mapper.UserMapper;
import com.gzist.security4.service.RoleService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class UmsUserDetailsService implements UserDetailsService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private RoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //先进行自定义登录数据源
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            //当查询结果为空说明账号错误，手动抛出业务一场
            throw new UsernameNotFoundException("账号错误！！！");
        }
        //将其下所拥有得权限查询出来并存进去
        List<Role> roles = userMapper.getAllRoles(user.getId());
        Set<Long> roleIds = new HashSet<>();
        List<String> perms = user.getPerms();
        for (Role role : roles) {
            roleIds.add(role.getId());
        }
        List<Permission> permissions = roleService.getPermissionByRoleIds(roleIds);
        for (Permission permission : permissions) {
            String str = permission.getPerms();
            //在这里做判断是为了让权限标识集合不存在空字符串，防止权限获取的时候出错
            if (StringUtils.hasLength(str)) {
                perms.add(str);
            }
        }
        return user;
    }
}
